/*
 * @lc app=leetcode.cn id=199 lang=cpp
 *
 * [199] 二叉树的右视图
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        if (root == nullptr)
            return {};

        std::vector<int> result;
        std::queue<TreeNode*> nodes;
        nodes.push(root);

        int num = 1;
        while (!nodes.empty()) {
            int thisLevel = 0;
            for (int i = 0; i < num; i++) {
                auto node = nodes.front();
                nodes.pop();

                if (node->left != nullptr) {
                    nodes.push(node->left);
                    thisLevel++;
                }
                if (node->right != nullptr) {
                    nodes.push(node->right);
                    thisLevel++;
                }

                //判断该层最右节点
                if (i == num - 1)
                    result.push_back(node->val);
            }
            num = thisLevel;
        }

        return result;
    }
};
// @lc code=end

